package com.entrogy.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.entrogy.bean.PubCountEntity;
import com.entrogy.bean.StudentEntity;
import com.entrogy.bean.TeacherBasicInfoEntity;
import com.entrogy.dao.*;
import com.entrogy.service.LeaveService;
import com.entrogy.utils.SendUtils;
import com.entrogy.utils.StrUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class LeaveServiceImpl implements LeaveService{

	private static final Logger logger = LoggerFactory.getLogger(LeaveServiceImpl.class);

	@Autowired
	private LeaveMapper leaveMapper;
	@Autowired
	private MessageMapper messageMapper;
	@Autowired
	private CheckTimeMapper checkTimeMapper;
	@Autowired
	private SchoolMapper schoolMapper;

	@Autowired
	private StudentMapper studentMapper;

	@Autowired
	private UserMapper userMapper;

	@Autowired
	private PositionMapper positionMapper;

	// 请假页面初始化
	public JSONObject leaveInit(String uid) {
		JSONObject jsonObject = new JSONObject();
		SimpleDateFormat sformat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		if (uid.startsWith("1")) { //老师
				int count = leaveMapper.leaveRevodeCount(uid, null);
				jsonObject.put("total", count);
			List<Map<String,Object>> leaveLst =  leaveMapper.getLeaveRecordBean(uid, 0, 10, null);
				jsonObject.put("pagenum", leaveLst.size());
				jsonObject.put("eachpage", "10");
				JSONArray array = new JSONArray();
				for (Map<String,Object> tmpBean : leaveLst) {
					JSONObject tmp = new JSONObject();
					tmp.put("id", tmpBean.get("leave_id").toString());
					String parentName = "";
					if(uid.startsWith("1")){
						parentName = leaveMapper.userTeacherName(tmpBean.get("parent_id").toString());
					}else {
						parentName = leaveMapper.userParentName(tmpBean.get("parent_id").toString());
					}
					tmp.put("parent", parentName);
					String stuName = leaveMapper.getStuName(Integer.parseInt(tmpBean.get("student_id").toString()));
					tmp.put("name", stuName);
					tmp.put("time", sformat.format(tmpBean.get("leave_time")));
					tmp.put("s_time", sformat.format(tmpBean.get("start_time")));
					tmp.put("e_time", sformat.format(tmpBean.get("end_time")));
					tmp.put("content", tmpBean.get("leave_content"));
					tmp.put("deal", tmpBean.get("isauthority"));
					array.add(tmp);
				}
				jsonObject.put("list", array);
		} else if (uid.startsWith("3")) { //家长
				Long count = leaveMapper.leaveRevodeCountByParnet(uid, null);
				jsonObject.put("total", count);
            List<Map<String,Object>> leaveLst =leaveMapper.getLeaveRecordBeanByParent(uid, 0, 10, null);
			/*	leaveLst = (ArrayList<LeaveRecordEntity>) */
				if (leaveLst!=null){
					jsonObject.put("pagenum", leaveLst.size());
					jsonObject.put("eachpage", "10");
					JSONArray array = new JSONArray();
					for (Map<String,Object> tmpBean : leaveLst) {
						JSONObject tmp = new JSONObject();
						tmp.put("id", tmpBean.get("leave_id"));
						String parentName = new String();
						if(uid.startsWith("1")){
                            if (tmpBean.get("parent_id")!=null && !"".equals(tmpBean.get("parent_id"))) {
                                parentName = leaveMapper.userTeacherName(tmpBean.get("parent_id").toString());
                            }
						}else {
                            if (tmpBean.get("parent_id")!=null && !"".equals(tmpBean.get("parent_id"))) {
                                parentName = leaveMapper.userParentName(tmpBean.get("parent_id").toString());
                            }
						}
						tmp.put("parent", parentName);
						String stuName ="";
						if (tmpBean.get("student_id")!=null && !"".equals(tmpBean.get("student_id"))){

							stuName = leaveMapper.getStuName(Integer.parseInt(tmpBean.get("student_id").toString()));
						}
						if (StringUtils.isNoneBlank(stuName)){
							tmp.put("name", stuName);
						}
						if (tmpBean.get("leave_time")!=null && !"".equals(tmpBean.get("leave_time"))){
                            tmp.put("time", tmpBean.get("leave_time").toString());
                        }
                        if (tmpBean.get("start_time")!=null && !"".equals(tmpBean.get("start_time"))){
                            tmp.put("s_time", tmpBean.get("start_time").toString());
                        }
                        if (tmpBean.get("end_time")!=null && !"".equals(tmpBean.get("end_time"))){
                            tmp.put("e_time", tmpBean.get("end_time").toString());
                        }
                        if (tmpBean.get("leave_content")!=null && !"".equals(tmpBean.get("leave_content"))){
                            tmp.put("content", tmpBean.get("leave_content").toString());
                        }
                        if (tmpBean.get("isauthority")!=null && !"".equals(tmpBean.get("isauthority"))){
                            tmp.put("deal", tmpBean.get("isauthority").toString());
                        }

						array.add(tmp);
					}
					jsonObject.put("list", array);
				}


		}
		return jsonObject;
	}

	// 处理家长请假申请
	/*
	 * 家长请假流程 1.读取信息 2.先在数据库查询是否有这个人，没有则返回出错信息 3.如果正常返回则将该条请假记录插入数据库，向对应的老师发送一条推送
	 * 4.正常返回给前端
	 */
	public String parentAskforLeave(String uid, String s_time, String e_time, String content, Integer studentId) {
		// 如果有问题直接就抛出异常了
		StudentEntity studentBeanNoBase64 = studentMapper.getStudentById(studentId);
		// 能顺利运行到下一行则说明是通过核对了，将该消息插入数据库
		PubCountEntity pubCountEntity;
		// 多职位切换备份
//		String teacher_id = leaveMapper.getBanzhuren(studentId);
		StudentEntity studentEntity = studentMapper.getStudentById(studentId);
		TeacherBasicInfoEntity teacher = positionMapper.getClassLeader(studentEntity.getCourseId(), studentEntity.getSchoolCode());
		try {
			leaveMapper.insertIntoLeaveRecord(uid, studentId, teacher.getTeacherId(),s_time, e_time, content);
		} catch (Exception e) {
			e.printStackTrace();
			return "插入请假记录表失败";
		}
		// 发送微信推送
		try {
			pubCountEntity = messageMapper.getPubCountOpenidByPhone(teacher.getMobile());
		} catch (Exception e) {
			e.printStackTrace();
			return "发送微信失败";
		}
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String schoolName = schoolMapper.getSchoolName(studentBeanNoBase64.getSchoolCode());
		String[] paramsWeiXin = { "", schoolName, studentBeanNoBase64.getStudentName() + "请假申请", format.format(date),
				"请假理由:" + content, "" };
		if (null != pubCountEntity && !StrUtils.isNullOrEmpty(pubCountEntity.getOpenid()))
			SendUtils.sendByWeixinAndPath(pubCountEntity, paramsWeiXin, pubCountEntity.getTemplateId(), "packageA/pages/leave/leave?ltype=leave&utype=2");
		return null;
	}

	// 请假页面翻页
	public JSONObject leaveNewPage(String uid, int currentPage, int pageSize, Integer selectType) {
		JSONObject jsonObject = new JSONObject();
		SimpleDateFormat sformat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
		if (uid.startsWith("1")) {
			try {
				Integer total = leaveMapper.leaveRevodeCount(uid, selectType);
				if (total!=null) {
					jsonObject.put("total", total);
				}
				List<Map<String,Object>> leaveLst =  leaveMapper.getLeaveRecordBean(uid, (currentPage - 1) * 10, pageSize, selectType);
				jsonObject.put("pagenum", leaveLst.size());
				JSONArray array = new JSONArray();
				if (leaveLst!=null) {
					for (Map<String,Object> tmpBean : leaveLst) {
						JSONObject tmp = new JSONObject();
						tmp.put("id",  tmpBean.get("leave_id") );
						String parentName="";
						if (!"".equals(tmpBean.get("parent_id")) && tmpBean.get("parent_id")!=null) {
						 parentName = leaveMapper.userParentName(tmpBean.get("parent_id").toString());
						}
						tmp.put("parent", parentName);
						String stuName="";
						if (!"".equals(tmpBean.get("student_id")) && tmpBean.get("student_id")!=null) {
							 stuName = leaveMapper.getStuName(Integer.parseInt(tmpBean.get("student_id").toString()));
						}
						tmp.put("name", stuName);
						if (tmpBean.get("leave_time")!=null && !"".equals(tmpBean.get("leave_time"))) {
							tmp.put("time",  sformat.format(tmpBean.get("leave_time")));
						}if (tmpBean.get("start_time")!=null && !"".equals(tmpBean.get("start_time"))) {
							tmp.put("s_time", sformat.format(tmpBean.get("start_time")));
						}
						if (tmpBean.get("end_time")!=null && !"".equals(tmpBean.get("end_time"))) {
							tmp.put("e_time", sformat.format(tmpBean.get("end_time")));
						}

						tmp.put("content", tmpBean.get("leave_content"));
						tmp.put("deal", tmpBean.get("isauthority"));
						array.add(tmp);
					}
				}
				jsonObject.put("list", array);
			} catch (Exception e) {
				e.printStackTrace();
				jsonObject.put("errcode", 1);
				jsonObject.put("errmsg", "获取请假页面翻页数据失败");
				logger.error("newPage:" + uid + " " + currentPage);
				return jsonObject;
			}
		} else if (uid.startsWith("3")) {
			try {
				Long count = leaveMapper.leaveRevodeCountByParnet(uid, selectType);
				jsonObject.put("total", count);
				List<Map<String,Object>> leaveLst1=leaveMapper.getLeaveRecordBeanByParent(uid, (currentPage - 1) * 10, pageSize, selectType);
				jsonObject.put("pagenum", leaveLst1.size());
				JSONArray array = new JSONArray();
				if (leaveLst1!=null){
				for (Map<String,Object> tmpBean : leaveLst1) {
					JSONObject tmp = new JSONObject();
					tmp.put("id", tmpBean.get("leave_id"));
					String parentName="";
					if (!"".equals(tmpBean.get("parent_id")) && tmpBean.get("parent_id")!=null) {
						 parentName = leaveMapper.userParentName(tmpBean.get("parent_id").toString());
					}
					tmp.put("parent", parentName);
					String stuName="";
					if (!"".equals(tmpBean.get("student_id")) && tmpBean.get("student_id")!=null) {
					 stuName = leaveMapper.getStuName(Integer.parseInt(tmpBean.get("student_id").toString()));
					}
					tmp.put("name", stuName);
					if (tmpBean.get("leave_time")!=null && !"".equals(tmpBean.get("leave_time"))) {
						tmp.put("time",  sformat.format(tmpBean.get("leave_time")));
					}
					if (tmpBean.get("start_time")!=null && !"".equals(tmpBean.get("start_time"))) {
						tmp.put("s_time", sformat.format(tmpBean.get("start_time")));
					}
					if (tmpBean.get("end_time")!=null && !"".equals(tmpBean.get("end_time"))) {
						tmp.put("e_time", sformat.format(tmpBean.get("end_time")));
					}

					tmp.put("content", tmpBean.get("leave_content"));
					tmp.put("deal", tmpBean.get("isauthority"));
					array.add(tmp);
				}
				}
				jsonObject.put("list", array);
			} catch (Exception e) {
				e.printStackTrace();
				jsonObject.put("errcode", 1);
				jsonObject.put("errmsg", "获取翻页数据失败");
				logger.error("newPage:" + uid + " " + currentPage);
				return jsonObject;
			}
		}
		jsonObject.put("errcode", 0);
		jsonObject.put("errmsg", "ok");
		return jsonObject;
	}

	/*
	 * 请假审核 1.更新数据表 2.给家长微信推送审核结果
	 */
	@Override
	public JSONObject check(String uid, String listId, int deal) {
		JSONObject returnObj = new JSONObject();
			// 更新数据表
			String parentid = null;
			String content = null;
			PubCountEntity pubCountEntity = null;
			String teacherName = null;
			try {
				 leaveMapper.updateLeaveRecord(listId, deal);
				 parentid = leaveMapper.getParentId(listId);
				returnObj.put("errcode", 1);
				returnObj.put("errmsg", "提交审核成功");
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("更新请假记录失败");
				returnObj.put("errcode", 0);
				returnObj.put("errmsg", "提交审核失败");
				logger.error("check:" + uid + " " + listId + " " + deal);
				return returnObj;
			}
			// 给家长发送微信推送
			try {
				pubCountEntity = messageMapper.getPubCountOpenidByid(parentid);
			} catch (Exception e1) {
				e1.printStackTrace();
				System.out.println("查询家长微信openid失败");
				returnObj.put("errcode", 1);
				returnObj.put("errmsg", "提交审核失败");
				logger.error("check:" + uid + " " + listId + " " + deal);
				return returnObj;
			}
			Date date = new Date();
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			if (deal == 1)
				content = "班主任已审核通过";
			else
				content = "请假申请已被拒绝";
			try {
				teacherName = leaveMapper.userTeacherName(uid);
			} catch (Exception e) {
				e.printStackTrace();
				logger.error("查询教师姓名失败");
				returnObj.put("errcode", 1);
				returnObj.put("errmsg", "提交审核失败");
				logger.error("check:" + uid + " " + listId + " " + deal);
				return returnObj;
			}
			Integer schoolCode = userMapper.getSchoolCodeByUserId(uid);
			String schoolName = schoolMapper.getSchoolName(schoolCode);
			String[] paramsWeiXin = { "", schoolName, teacherName, format.format(date), "请假审核状态:" + content, "" };
			if (null != pubCountEntity && !StrUtils.isNullOrEmpty(pubCountEntity.getOpenid()))
				SendUtils.sendByWeixinAndPath(pubCountEntity, paramsWeiXin, pubCountEntity.getTemplateId(), "packageA/pages/leave/leave?ltype=leave&utype=1");
			returnObj.put("errcode", 0);
			returnObj.put("errmsg", "ok");
			return returnObj;
	}



    // 核对请假人信息
	private StudentEntity checkParentandStudnet(String parentid, String stu_name) throws Exception {
		StudentEntity studentBean = null;
		try {
			studentBean = leaveMapper.getStuKeyInfo(parentid, stu_name);
			if (studentBean == null)
				throw new Exception("核对学生信息失败");
		} catch (SQLException e) {
			e.printStackTrace();
			throw new Exception("核对学生信息失败");
		}
		return studentBean;
	}

    /**
     *  保安获取学生请假信息
     * @param course_id
     * @param schoolCode
     * @param selectDate
	 * @param isAgree
	 * @return
     */
	// 保安队长查询请假学生信息
    @Override
	public List<JSONObject> getLeaveRecord(String course_id, String schoolCode, String selectDate, Integer isAgree)  {
        List<JSONObject> jsonArray = new ArrayList<>();
		// 查询出 每个班的请假学生
		List<Map<String,Object>> leaveRecordBeans = getLeaveRecordList(course_id, schoolCode, selectDate, isAgree);
		for (Map<String,Object> leaveRecordBean : leaveRecordBeans) {
			JSONObject tmp = new JSONObject();
			tmp.put("id", leaveRecordBean.get("leave_id"));
			tmp.put("col1", null);
			tmp.put("col2", leaveRecordBean.get("class_name"));
			tmp.put("col3", leaveRecordBean.get("student_name"));
			if ((leaveRecordBean.get("isauthority").toString()).equals("1")) {
				tmp.put("col4", "已审批");
			} else {
				tmp.put("col4", "未审批");
			}
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			if (leaveRecordBean.get("start_time") != null && !"".equals(leaveRecordBean.get("start_time"))) {
				tmp.put("col5", dateFormat.format(leaveRecordBean.get("start_time")));
			}
			jsonArray.add(tmp);
		}
		return jsonArray;
	}

	// 根据年级班级ID查询出其班主任ID 在查询出对应班级的请假学生
	public List<Map<String,Object>> getLeaveRecordList(String course_id, String schoolCode, String selectDate, Integer isAgree) {
		Map<String,Object> map = new HashMap<>();
		map.put("course_id", course_id);
		map.put("schoolCode", schoolCode);
		map.put("selectDate", selectDate);
		map.put("isAgree", isAgree);
		return checkTimeMapper.getLeaveRecordList(map);
	}



}
